<?php
namespace app\admin\controller;
use app\admin\model\Users as UsersModel;
class Users extends Common{
    //会员列表
    public function index(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('users')->alias('u')
                ->join(config('database.prefix').'user_level ul','u.level = ul.level_id','left')
                ->field('u.*,ul.level_name')
                ->where('u.Nickname|u.mobile|u.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['reg_time'] = date('Y-m-d H:i:s',$v['reg_time']);
                $list['data'][$k]['jihuo_time'] = date('Y-m-d H:i:s',$v['jihuo_time']);
                $tlevel=gettlevel($v['tlevel']);
                if($v['area3']==1){
                    $list['data'][$k]['tlevel_name']="县级代理";
                }elseif($v['yarea3']==1){
                    $list['data'][$k]['tlevel_name']="市级代理";
                }elseif($v['narea3']==1){
                    $list['data'][$k]['tlevel_name']="省级代理";
                }else{
                    $list['data'][$k]['tlevel_name']="无";
                }

				 if(!empty($v['up_userid'])){
					 $upuser=db('users')->where('id='.$v['up_userid'])->value('nickname');
					$list['data'][$k]['up_userid']=$upuser;
				}else{
					$list['data'][$k]['up_userid']='空';
				}
				if(!empty($v['fatherid'])){
					 $upuser=db('users')->where('id='.$v['fatherid'])->value('nickname');
					$list['data'][$k]['fatherid']=$upuser;
				}else{
					$list['data'][$k]['fatherid']='空';
				}
				if(!empty($v['center_id'])){
				 $upuser2=db('users')->where('id='.$v['center_id'])->value('nickname');
				 $list['data'][$k]['center_id']=$upuser2;
				}else{
					$list['data'][$k]['center_id']='空';
				}
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $money_config=db('money_config')->select();
        $this->assign('money_jifen',$money_config[0]['name']);
        $this->assign('money_qian',$money_config[1]['name']);
        $this->assign('money_benjin',$money_config[2]['name']);
        $this->assign('money_qita',$money_config[3]['name']);
        $this->assign('money_baodan',$money_config[4]['name']);
        return $this->fetch();
    }
    public function user_daochu(){
        require 'daochu.php';
        user_daochu_jb();
        exit;
       /* header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=table.xls");
        $str="会员编号\t会员姓名\t会员等级\t团队等级\t联系电话\t推荐人\t服务中心\t余额\t报单币\t推荐人数\t状态\t锁定状态\t注册时间\t激活时间\t\n";
        echo $str;
        $list=db('users')
            ->where('id','gt',0)
            ->select();

        foreach($list as $key=>$row){
            echo $row['nickname']."\t";
            echo $row['username']."\t";
            echo "普通客户\t";
            $lname=db('user_tlevel')->where('level',$row['tlevel'])->value('level_name');
            echo "'".$lname."'"."\t";
            echo $row['mobile']."\t";
            $nickname=db('users')->where('id',$row['up_userid'])->value('nickname');
            echo $nickname."\t";
            $center_id=db('users')->where('id',$row['center_id'])->value('nickname');
            echo $center_id."\t";

            echo $row['money_jifen']."\t";
            echo $row['money_baodan']."\t";
            echo $row['recount']."\t";

            if ($row['activation']==1){
                echo "已激活\t";
            }elseif($row['activation']==0){
                echo "未激活\t";
            }
            if ($row['is_lock']==1){
                echo "已锁定\t";
            }elseif($row['is_lock']==0){
                echo "未锁定\t";
            }
            echo date('Y-m-d H:i:s',$row['reg_time'])."\t";
            echo date('Y-m-d H:i:s',$row['jihuo_time'])."\t\n";
        }
        exit;*/



    }
	
	public function tixian(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $start_time=strtotime(input('post.start_time')) ;
            $end_time=strtotime(input('post.end_time'));
            if(!empty($start_time)||!empty($end_time)){
                $where="u.tixian_time >= ".$start_time ." and u.tixian_time <=".$end_time;
            }else{
                $where="";
            }
            $list=db('tixian')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.tixian_time,u.shoutype,u.is_lock,u.type,u.is_ok,u.userid,u.shifa_qian,ul.*')
                ->where('ul.nickname|ul.mobile|ul.username','like',"%".$key."%")
                ->where($where)
                ->order('u.tixian_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
				
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['tixian_time'] = date('Y-m-d H:i:s',$v['tixian_time']);
                $list['data'][$k]['type_name']=tixiantype($v['type']);
                if($v['shoutype']==1){
                    $list['data'][$k]['shoutype']="银行卡";
                }elseif($v['shoutype']==2){
                    $list['data'][$k]['shoutype']="支付宝";
                }elseif($v['shoutype']==3){
                    $list['data'][$k]['shoutype']="微信";
                }
                $list['data'][$k]['zhifubao_content'] ="支付宝收款码";
                $list['data'][$k]['wechat_content'] ="微信收款码";
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    public function daochu(){
        require 'daochu.php';
        $key=input('key');
        $test1=strtotime(input('test1'));
        $test2=strtotime(input('test2'));
        tixian_daochu($key,$test1,$test2);
        exit;
       /* header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=table.xls");
        $str="会员编号\t会员手机号\t开户银行\t开户帐号\t开户姓名\t开户地址\t提现类型\t收款类型\t提现金额\t实发金额\t提现时间\t审核状态\t\n";
        echo $str;
        $list=db('tixian')
            ->alias('u')
            ->join('__USERS__ ul','ul.id = u.userid','left')
            ->field('u.id as bid,u.num,u.tixian_time,u.shoutype,u.is_lock,u.type,u.is_ok,u.userid,u.shifa_qian,ul.*')
            ->where('u.id','gt',0)
            ->select();

        foreach($list as $key=>$row){
            echo $row['nickname']."\t";
            echo $row['mobile']."\t";
            echo $row['bank_name']."\t";
            echo "'".$row['bank_card']."'"."\t";
            echo $row['username']."\t";
            echo $row['bank_dizhi']."\t";
            echo tixiantype($row['type'])."\t";
            if($row['shoutype']==1){
                echo "银行卡"."\t";
            }elseif($row['shoutype']==2){
                echo "支付宝"."\t";
            }elseif($row['shoutype']==3){
                echo "微信"."\t";
            }
            echo $row['num']."\t";
            echo $row['shifa_qian']."\t";
            echo date('Y-m-d H:s',$row['tixian_time'])."\t";
            if ($row['is_ok']==1){
                echo "已通过\t\n";
            }elseif($row['is_ok']==2){
                echo "已驳回\t\n";
            }else{
                echo "审核中\t\n";
            }
        }
        exit;*/
    }
    public function chongzhi(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('chongzhi')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.uid','left')
                ->field('u.id as bid,u.jine,u.cdate,u.isgrant,u.pzimg,u.lx,ul.*')
                ->where('ul.nickname|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.cdate desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['cdate'] = date('Y-m-d H:i:s',$v['cdate']);
                $list['data'][$k]['lx'] =tixiantype($v['lx']);
                $list['data'][$k]['zhifu_content'] ="支付凭证";
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    public function chongzhi_ok(){
        if(request()->isPost()){
            $id=input('post.id');
            $chongzhi=db('chongzhi')->where('id',$id)->find();
            $str=db('money_config')->where('id',$chongzhi['lx'])->value('varname');
            db('users')->where('id',$chongzhi['uid'])->setInc($str,$chongzhi['jine']);
            db('chongzhi')->where('id',$id)->setField('isgrant',2);
        }
        return array('code'=>1,'msg'=>'确认成功');
    }

    public function chongzhi_false(){
        if(request()->isPost()){
            $id=input('post.id');
            /*            $chongzhi=db('chongzhi')->where('id',$id)->find();
                        $str=db('money_config')->where('id',$chongzhi['lx'])->value('varname');
                        db('users')->where('id',$chongzhi['uid'])->setInc($str,$chongzhi['jine']);*/
            db('chongzhi')->where('id',$id)->setField('isgrant',-1);
        }
        return array('code'=>1,'msg'=>'确认成功');
    }
    //会员积分日志// 资金记录日志
	public function money_log(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
			
            $list=db('money_log')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.time,u.type,u.source,u.beizhu,u.userid,u.dangqian,ul.*')
                ->where('ul.nickname|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.id desc,u.time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['time'] = date('Y-m-d H:i:s',$v['time']);
                $list['data'][$k]['type_name']=money_log_type($v['source']);
                $list['data'][$k]['type']=tixiantype($v['type']);
                //变动类型处理 预留


            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }

    public function money_log_daochu(){

        require 'daochu.php';
        $key=input('key');
        money_log_daochu($key);
        exit;
       /* header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=table.xls");
        $str="会员编号\t会员手机号\t会员姓名\t变动类型\t资金类型\t金额变动\t当前余额\t时间\t备注\t\n";
        echo $str;
        $list=db('money_log')
            ->alias('u')
            ->join('__USERS__ ul','ul.id = u.userid','left')
            ->field('u.id as bid,u.num,u.time,u.type,u.source,u.beizhu,u.userid,u.dangqian,ul.*')
            ->where('u.id','gt',0)
            ->select();

        foreach($list as $key=>$row){
            echo $row['nickname']."\t";
            echo $row['mobile']."\t";
            echo $row['username']."\t";
            $type_name=money_log_type($row['source']);
            echo "'".$type_name."'"."\t";
            $type=tixiantype($row['type']);
            echo $type."\t";
            echo $row['num']."\t";
            echo $row['dangqian']."\t";
            echo date('Y-m-d H:i:s',$row['time'])."\t";
            echo $row['beizhu']."\t\n";
        }
        exit;*/



    }
    //复投记录
    public function redelivery_log(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('redelivery')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.uid','left')
                ->field('u.id as bid,u.mey,u.createtime,u.nickname as unicknme,u.uid as uuid,ul.*')
                ->where('ul.nickname|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
             if(!empty($list)){
                 foreach ($list['data'] as $k=>$v){
                     $list['data'][$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                 }
             }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    //交易大厅记录
    public function guamai_log(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('guamai')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.uid','left')
                ->field('u.id as bid,u.num,u.price,u.is_ok,u.gid,u.gnickname,u.createtime as utime,u.unickname,u.uid as uuid,ul.*')
                ->where('ul.nickname|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
             if(!empty($list)){
                 foreach ($list['data'] as $k=>$v){
                     $list['data'][$k]['utime'] = date('Y-m-d H:i:s',$v['utime']);
                 }
             }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    //交易大厅记录(我的购买)
    public function my_buy_log(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('my_buy')
                ->alias('u')
                ->join('__USERS__ ul','ul.id = u.gid','left')
                ->field('u.id as bid,u.num,u.price,u.is_ok,u.gid,u.gnickname,u.createtime as utime,u.unickname,u.uid as uuid,ul.*')
                ->where('ul.nickname|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            if(!empty($list)){
                foreach ($list['data'] as $k=>$v){
                    $list['data'][$k]['utime'] = date('Y-m-d H:i:s',$v['utime']);
                }
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    //匹配
    public function pipei(){
        $id=input('id');
        $buy=db('my_buy')->where('id',$id)->find();//买入会员
        if($buy['is_ok']!=1){
            return array('code'=>0,'msg'=>'当前不能匹配');exit;
        }
        $guamai_count=db('guamai')->where('is_ok',1)->count();//卖的会员
        if(empty($guamai_count)||$guamai_count==0){
            return array('code'=>0,'msg'=>'当前没有可匹配的订单');exit;
        }
        $guamai=db('guamai')->where('is_ok',1)->order('createtime,id asc')->find();//卖的会员

        if($guamai['num']>$buy['num']){
            /*
             * 匹配成功的那条
             */
            $dt=array(
                'uid'=>$guamai['uid'],
                'num'=>$buy['num'],
                'price'=>$guamai['price'],
                'sxf'=>$guamai['sxf'],
                'is_ok'=>2,
                'unickname'=>$guamai['nickname'],
                'gid'=>$buy['gid'],
                'gnickname'=>$buy['gickname'],
                'createtime'=>time(),
                'shopid'=>$buy['id']
            );
            db('guamai')->where('id',$guamai['id'])->update($dt);
            /*
             *剩下的继续交易的那条
             */
            $cha=$guamai['num']-$buy['num'];
            $dt=array(
                'uid'=>$guamai['uid'],
                'num'=>$cha,
                'price'=>$guamai['price'],
                'sxf'=>$guamai['sxf'],
                'is_ok'=>1,
                'unickname'=>$guamai['unickname'],
                'createtime'=>time()
            );
            db('guamai')->insert($dt);
            /*
             *买入会员的操作
             */
            $array=array(
                'uid'=>$guamai['uid'],
                'unickname'=>$guamai['unickname'],
                'createtime'=>time(),
                'is_ok'=>2,
                'shopid'=>$guamai['id']
            );
            db('my_buy')->where('id',$buy['id'])->update($array);

        }elseif($guamai['num']==$buy['num']){
            /*
                * 匹配成功的那条
                */
            $dt=array(
                'uid'=>$guamai['uid'],
                'num'=>$guamai['num'],
                'sxf'=>$guamai['sxf'],
                'is_ok'=>2,
                'gid'=>$buy['gid'],
                'gnickname'=>$buy['gnickname'],
                'createtime'=>time(),
                'shopid'=>$buy['id'],
            );
            db('guamai')->where('id',$guamai['id'])->update($dt);


            /*
            *买入会员的操作
            */
            $array=array(
                'uid'=>$guamai['uid'],
                'unickname'=>$guamai['unickname'],
                'createtime'=>time(),
                'is_ok'=>2,
                'shopid'=>$guamai['id'],
            );
            db('my_buy')->where('id',$buy['id'])->update($array);
        }else{
            /*
             * 匹配成功的那条
             */
            $dt=array(
                'sxf'=>$guamai['sxf'],
                'is_ok'=>2,
                'gid'=>$buy['gid'],
                'gnickname'=>$buy['gnickname'],
                'createtime'=>time(),
                'shopid'=>$buy['id'],
            );
            db('guamai')->where('id',$guamai['id'])->update($dt);


            /*
             *买入会员的操作
             */
            $array=array(
                'uid'=>$guamai['uid'],
                'num'=>$guamai['num'],
                'unickname'=>$guamai['unickname'],
                'createtime'=>time(),
                'is_ok'=>2,
                'shopid'=>$guamai['id'],
            );

            db('my_buy')->where('id',$buy['id'])->update($array);
            /*
                    *剩下的继续交易的那条
                    */
            $cha=$buy['num']-$guamai['num'];
            $dt=array(
                'gid'=>$buy['gid'],
                'num'=>$cha,
                'price'=>$buy['price'],
                'is_ok'=>1,
                'gnickname'=>$buy['gnickname'],
                'createtime'=>time()
            );
            db('my_buy')->insert($dt);
        }
        return $result = ['code'=>1,'msg'=>'匹配成功!'];
    }
	public function baodanlist(){
	
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
			
            $list=db('baodan')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.baodan_time,u.is_lock,u.type,u.is_ok,u.userid,ul.*')
                ->where('ul.email|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.baodan_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
				
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['baodan_time'] = date('Y-m-d H:i:s',$v['baodan_time']);
				//判断报单中心是否存在
				if(!empty($v['center_id'])){
					
					$upuser=db('users')->where('id='.$v['center_id'])->value('mobile');
					$list['data'][$k]['center_id']=$upuser;
				}
				
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    public function baodan_log(){

        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('money_log')
                ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.time,u.beizhu,ul.*')
                ->where('ul.email|ul.mobile|ul.username','like',"%".$key."%")
                ->where('u.source',8)
                ->order('u.time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['time'] = date('Y-m-d H:i:s',$v['time']);


                    $upuser=db('users')->where('mobile',$v['beizhu'])->order('id asc')->find();
                    $list['data'][$k]['nick_name']=$upuser['username'];
                    $list['data'][$k]['id_card']=$upuser['shenfenzheng'];
                    $list['data'][$k]['address']=$upuser['dizhi'];


            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    public function dingdanlist(){

        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('shop_dingdan')
                ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.*,ul.nickname,ul.mobile,ul.username,ul.province,ul.city,ul.district,ul.dizhi,u.id as bid')
                ->where('ul.nickname|ul.mobile|ul.username','like',"%".$key."%")->where('pay_ok=1')
                ->order('u.time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            foreach ($list['data'] as $k=>$v){
                if($v['pay_type']==1){
                    $list['data'][$k]['pay_type']='金额';
                }elseif($v['pay_type']==2){
                    $list['data'][$k]['pay_type']='复销积分';
                }else{
                    if($v['pay_type']=='zfb'){
                        $list['data'][$k]['pay_type']='支付宝';
                    }elseif($v['pay_type']=='weixin'){
                        $list['data'][$k]['pay_type']='微信';
                    }
                }
                $list['data'][$k]['time'] = date('Y-m-d H:i:s',$v['time']);
                $list['data'][$k]['pay_time'] = date('Y-m-d H:i:s',$v['pay_time']);
                $list['data'][$k]['thumb']=db('shop')->where('id',$v['shop_id'])->value('thumb');
                $list['data'][$k]['proname']=db('shop')->where('id',$v['shop_id'])->value('title');
                $province=$this->get_region($v['province']);
                $city=$this->get_region($v['city']);
                $district=$this->get_region($v['district']);
                $list['data'][$k]['dizhi']=$province['name'].$city['name'].$district['name'].$v['dizhi'];

            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    public function get_region($id){
        $region=db('region')->where('id',$id)->find();
        return $region;
    }
    //完成发货
    public function fahuo(){
        $id=input('id');
        db('shop_dingdan')->update(['id' => $id, 'is_ok' => '3']);
        // 此处写发货完成之后的算法
        return $result = ['code'=>1,'msg'=>'发货成功!'];
    }
    //取消发货
    public function quxiaofahuo(){
        $id=input('id');
        db('shop_dingdan')->update(['id' => $id, 'is_ok' => '5']);
        // 此处写取消完成之后的算法
        return $result = ['code'=>1,'msg'=>'取消发货成功!'];
    }
    //设置会员状态
    public function usersState(){
        $id=input('post.id');
        $is_lock=input('post.is_lock');
        $user=getuser($id);
        if($user['activation']==1){
            return ['status'=>0,'msg'=>'该会员已激活!'];
        }else{
            if(db('users')->where('id='.$id)->update(['activation'=>$is_lock])!==false){
                jihuo($id,1);
                return ['status'=>1,'msg'=>'设置成功!'];
            }else{
                return ['status'=>0,'msg'=>'设置失败!'];
            }
        }
    }
    public function user_lock(){
        $id=input('post.id');
        $lock=input('post.lock');
        if(db('users')->where('id',$id)->update(['is_lock'=>$lock])!==false){
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }

    }
	 public function tixians(){
        $id=input('post.id');
        $is_lock=input('post.is_lock');
	
        if(db('tixian')->where('id='.$id)->update(['is_ok'=>$is_lock])!==false){
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }

    public function edit($id=''){
        if(request()->isPost()){
            $user = db('users');
            $data = input('post.');
            $level =explode(':',$data['level']);
            $data['level'] = $level[1];
            $tlevel =explode(':',$data['tlevel']);
            $data['tlevel'] = $tlevel[1];
            $province =explode(':',$data['province']);
            $data['province'] = isset( $province[1])?$province[1]:'';
            $city =explode(':',$data['city']);
            $data['city'] = isset( $city[1])?$city[1]:'';
            $district =explode(':',$data['district']);
            $data['district'] = isset( $district[1])?$district[1]:'';
            if(empty($data['level'])){
                $data['level']=0;
            }
            if(empty($data['tlevel'])){
                $data['tlevel']=0;
            }
			//判断积分是否被修改
			$userinfo=db('users')->where('id='.$id)->find();
			//此处写的很乱，有时间的时候重新封装算法  2018年8月1日19:05:51
            if(!empty($data['money_jifen_type'])){
                $addinfo['type']=1; //1为积分 2为 金钱 3 为本金  4 为其他
                $addinfo['userid']=$userinfo['id'];
                $addinfo['dangqian']=$data['money_jifen'];
                $addinfo['source']=4;//4 为管理员操作
                $addinfo['time']=time();
                $addinfo['num']=$data['money_jifen_type'];
                $addinfo['beizhu']=$data['beizhu1'];
                db('money_log')->insert($addinfo);
                $data['money_jifen']=$userinfo['money_jifen']+$data['money_jifen_type'];
            }
            if(!empty($data['money_qian_type'])){
                $addinfo['type']=2; //1为积分 2为 金钱 3 为本金  4 为其他
                $addinfo['userid']=$userinfo['id'];
                $addinfo['dangqian']=$data['money_qian'];
                $addinfo['source']=4;//4 为管理员操作
                $addinfo['time']=time();
                $addinfo['num']=$data['money_qian_type'];
                $addinfo['beizhu']=$data['beizhu2'];
                db('money_log')->insert($addinfo);
                $data['money_qian']=$userinfo['money_qian']+$data['money_qian_type'];
            }
            if(!empty($data['money_benjin_type'])){
                $addinfo['type']=3; //1为积分 2为 金钱 3 为本金  4 为其他
                $addinfo['userid']=$userinfo['id'];
                $addinfo['dangqian']=$data['money_benjin'];
                $addinfo['source']=4;//4 为管理员操作
                $addinfo['time']=time();
                $addinfo['num']=$data['money_benjin_type'];
                $addinfo['beizhu']=$data['beizhu3'];
                db('money_log')->insert($addinfo);
                $data['money_benjin']=$userinfo['money_benjin']+$data['money_benjin_type'];
            }
            if(!empty($data['money_qita_type'])){
                $addinfo['type']=4; //1为积分 2为 金钱 3 为本金  4 为其他
                $addinfo['userid']=$userinfo['id'];
                $addinfo['dangqian']=$data['money_qita'];
                $addinfo['source']=4;//4 为管理员操作
                $addinfo['time']=time();
                $addinfo['num']=$data['money_qita_type'];
                $addinfo['beizhu']=$data['beizhu4'];
                db('money_log')->insert($addinfo);
                $data['money_qita']=$userinfo['money_qita']+$data['money_qita_type'];
            }
            if(!empty($data['money_baodan_type'])){
                $addinfo['type']=5; //1为积分 2为 金钱 3 为本金  4 为其他
                $addinfo['userid']=$userinfo['id'];
                $addinfo['dangqian']=$data['money_baodan'];
                $addinfo['source']=4;//4 为管理员操作
                $addinfo['time']=time();
                $addinfo['num']=$data['money_baodan_type'];
                $addinfo['beizhu']=$data['beizhu5'];
                db('money_log')->insert($addinfo);
                $data['money_baodan']=$userinfo['money_baodan']+$data['money_baodan_type'];
            }
            unset($data['money_jifen_type']);
            unset($data['money_qian_type']);
            unset($data['money_benjin_type']);
            unset($data['money_qita_type']);
            unset($data['money_baodan_type']);
            unset($data['beizhu1']);
            unset($data['beizhu2']);
            unset($data['beizhu3']);
            unset($data['beizhu4']);
            unset($data['beizhu5']);
            if(empty($data['password'])){
                unset($data['password']);
            }else{
                $data['password'] = md5($data['password']);
            }
            if(empty($data['twopassword'])){
                unset($data['twopassword']);
            }else{
                $data['twopassword'] = md5($data['twopassword']);
            }
            if ($user->update($data)!==false) {
                $result['msg'] = '会员修改成功!';
                $result['url'] = url('index');
                $result['code'] = 1;
            } else {
                $result['msg'] = '会员修改失败!';
                $result['code'] = 0;
            }
            return $result;
        }else{
            $province = db('Region')->where ( array('pid'=>1) )->select ();
            $user_level=db('user_level')->order('sort')->select();
            $user_tlevel=db('user_tlevel')->order('sort')->select();
            $info = UsersModel::get($id);
            $this->assign('info',json_encode($info,true));
            $this->assign('title',lang('edit').lang('user'));
            $this->assign('province',json_encode($province,true));
            $this->assign('user_level',json_encode($user_level,true));
            $this->assign('user_tlevel',json_encode($user_tlevel,true));

            $city = db('Region')->where ( array('pid'=>$info['province']) )->select ();
            $this->assign('city',json_encode($city,true));
            $district = db('Region')->where ( array('pid'=>$info['city']) )->select ();
            $this->assign('district',json_encode($district,true));
            $money_config=db('money_config')->select();
            $this->assign('money_config',$money_config);
            return $this->fetch();
        }
    }
//后台注册
    public function regist(){
        $levellist=db('user_level')->where('level_id','gt',0)->select();
        $this->assign('levels',$levellist);

        if(request()->isPost()) {
            $table = db('users');
            $data = input('post.');
            $username = $data['username'];
            $mobile = $data['mobile'];
            $nickname = $data['nickname'];
            $password = $data['password'];
            $bank_name = $data['bank_name'];
            $bank_dizhi = $data['bank_dizhi'];
            $bank_card = $data['bank_card'];
            $topmobi = $data['topmobi'];
            $centermobile = $data['center_id'];
            $shenfenzheng = $data['shenfenzheng'];
            $fathername = $data['fathername'];
            $treeplace = $data['treeplace'];
            $level = $data['level'];
            $info['level']=$level;
            if(!$nickname || !$password){
                return array('code'=>0,'msg'=>'请填写账号或密码');
            }
            if(empty($username )){
                return array('code'=>-1,'msg'=>'请输入姓名');
            }
            $info['username']=$username;

            if(empty($bank_name)){
                return array('code'=>-1,'msg'=>'请输入开户银行');
            }
            $info['bank_name']=$bank_name;
            if(empty($bank_dizhi )){
                return array('code'=>-1,'msg'=>'请输入开户支行');
            }
            $info['bank_dizhi']=$bank_dizhi;
            if(empty($bank_card)){
                return array('code'=>-1,'msg'=>'请输入银行卡号');
            }
            $info['bank_card']=$bank_card;



            if(empty($shenfenzheng )){
                return array('code'=>-1,'msg'=>'请输入身份证号');
            }
            $info['shenfenzheng']=$shenfenzheng;
            $user = $table->where("nickname",$nickname)->find();
            if($user){
                return array('code'=>0,'msg'=>'账号已存在!');
            }
            $info['nickname']=$nickname;
            $user = $table->where("mobile",$mobile)->find();
            if($user){
                return array('code'=>0,'msg'=>'手机号已存在!');
            }
            $info['mobile']=$mobile;

            if(empty($password)){
                return array('code'=>0,'msg'=>'密码不能为空!');
            }else{
                $info['password']=md5($password);
            }
            $alen=strlen($password);
            if($alen<6||$alen>12){
                return array('code'=>-1,'msg'=>'请输入6-12位的密码');
            }
            if(empty($topmobi)){
                return array('code'=>0,'msg'=>'推荐人编号不能为空！！！');
            }else{
                $reus = db('users')->where(array('nickname'=>$topmobi,'activation'=>1))->find();
                if(empty($reus)){
                    return array('code'=>0,'msg'=>'推荐人不存在或者未激活！');
                }else{
                    $rpath="".$reus['rpath'].$reus['id'].",";
                    $info['up_userid']=$reus['id'];
                    $info['rpath']=$rpath;
                }
            }
            if(empty($fathername)){
                return array('code'=>0,'msg'=>'安置人编号不能为空！！！');
            }else{
                $father = db('users')->where(array('nickname'=>$fathername,'activation'=>1))->find();
                if(empty($father)){
                    return array('code'=>0,'msg'=>'安置人不存在或者未激活！');
                }else{
                    $is_user=db('users')->where('fatherid',$father['id'])->where('treeplace',$treeplace)->find();
                    if(empty($is_user)){
                        $ppath="".$father['ppath'].$father['id'].",";
                        $info['fatherid']=$father['id'];
                        $info['ppath']=$ppath;
                        $info['plevel']=$father['plevel']+1;
                    }else{
                        return array('code'=>0,'msg'=>'该位置已有会员，请更换位置后注册！');
                    }

                }
            }
            if(empty($centermobile)){
                return array('code'=>0,'msg'=>'服务中心编号不能为空！！！');
            }else{
                $server = db('users')->where(array('nickname'=>$centermobile,'activation'=>1,'server'=>2))->find();
                if(empty($server)){
                    return array('code'=>0,'msg'=>'服务中心不存在或者未激活！');
                }else{
                    $info['center_id']=$server['id'];
                }
            }
            $info['reg_time'] = time();
            $info['treeplace'] = $treeplace;
            $uid = db('users')->insertGetId($info);
            db('users')->where('id',$uid)->setField('uid',$uid);
            if($treeplace==1){
                db('users')->where('id',$father['id'])->setField('leftid',$uid);
            }else{
                db('users')->where('id',$father['id'])->setField('rightid',$uid);
            }
            return array('code'=>1,'msg'=>'注册成功','url' => url('index/index'));

        }
        return view();
    }
    public function getRegion(){
        $Region=db("region");
        $pid = input("pid");
        $arr = explode(':',$pid);
        $map['pid']=$arr[1];
        $list=$Region->where($map)->select();
        return $list;
    }

    public function usersDel(){
        $id=input('id');
        $user=getuser($id);
        /*       echo $user['nickname'];
               die();*/
        if($user['activation']==0){
            db('users')->delete(['id'=>input('id')]);
            db('oauth')->delete(['uid'=>input('id')]);
            return $result = ['code'=>1,'msg'=>'删除成功!'];
        }else{
            return $result = ['code'=>0,'msg'=>'删除失败!已激活会员不能删除'];
        }

    }
    public function bohui(){
        $id=input('id');
        $this->assign('id',$id);
        return $this->fetch();
    }
	//提现驳回
	 public function bohuishenqing(){
         $id=input('tixian_id');
         $reson=input('reson');
         $tixian_array=array(
             'is_ok'=>2,
             'beizhu'=>$reson,
         );
         db('tixian')->where('id',$id)->update($tixian_array);
		// 驳回时原路退回提现的金额
		//获取类型以及金额
	    $fan=db('tixian')->where('id',$id)->find();
		
		//  jifen($type,$userid,$num，$source,$jiajian)
		//  type          1为积分    2为 金钱    3 为本金  4 为其他
		//  $source       1商城消费  2 会员提现  3会员转账  4 管理变动  5 手动充值  6 微信充值
		//  num           数值
		//  $jiajian     1 为 加       2为减
		//  返回结果     1、执行成功   2 余额不足
		//    if($fan['type']==1){
                jifen($fan['type'],$fan['userid'],$fan['num'],7,1,'');
          /*  }else{
                jifen($fan['type'],$fan['userid'],$fan['num'],7,1,'');
            }*/
        return $result = ['code'=>1,'msg'=>'申请已驳回!'];
    }
	//驳回报单申请
		public function bohuibaodan(){
		 $id=input('id');
		 $baodan=db('baodan')->where('id',$id)->find();
		 if($baodan['is_ok']==0){
             db('baodan')->update(['id' => $id, 'is_ok' => '2']);
             return $result = ['code'=>1,'msg'=>'申请已驳回!'];
         }else{
             return $result = ['code'=>-1];
         }
    }
	//完成报单
	 public function baodanok(){
		 $id=input('id');
         $baodan=db('baodan')->where('id',$id)->find();
		 if($baodan['is_ok']==0){
             db('baodan')->update(['id' => $id, 'is_ok' => '1']);
         //    $baodan=db('baodan')->where('id',$id)->find();
        //     jihuo($baodan['userid'],$baodan['num']);
             // 此处写报单完成之后的算法
             return $result = ['code'=>1,'msg'=>'打款成功!'];
         }else{
             return $result = ['code'=>-1,'msg'=>'打款成功!'];
         }
    }

	 public function dakuan(){
		 $id=input('id');
		 $tixian=db('tixian')->where('id',$id)->find();
         $level=getulevel(1);
         $user=getuser($tixian['userid']);
         $sys=getsystem();
         if($user['money_max']>$level['b12']){
             $fei2=$sys['shouxufei']/100*$tixian['num'];
            if($fei2>0){
                jifen(2,$user['id'],$fei2,11,1,"提现增加");
            }
         }

		    db('tixian')->update(['id' => $id, 'is_ok' => '1']);

        return $result = ['code'=>1,'msg'=>'打款成功!'];
    }
    public function delall(){
        $map[] =array('id','IN',input('param.ids/a'));
        db('users')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        $result['url'] = url('index');
        return $result;
    }

    /***********************************会员组***********************************/
    public function userGroup(){
        if(request()->isPost()){
            $userLevel=db('user_level');
            $list=$userLevel->order('sort')->select();
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        return $this->fetch();
    }

    public function groupAdd(){
        if(request()->isPost()){
            $data = input('post.');
            db('user_level')->insert($data);
            $result['msg'] = '会员组添加成功!';
            $result['url'] = url('userGroup');
            $result['code'] = 1;
            return $result;
        }else{
            $this->assign('title',lang('add')."会员组");
            $this->assign('info','null');
            return $this->fetch('groupForm');
        }
    }

    public function groupEdit(){
        if(request()->isPost()) {
            $data = input('post.');
            db('user_level')->update($data);
            $result['msg'] = '会员组修改成功!';
            $result['url'] = url('userGroup');
            $result['code'] = 1;
            return $result;
        }else{
            $map['level_id'] = input('param.level_id');
            $info = db('user_level')->where($map)->find();
            $this->assign('title',lang('edit')."会员组");
            $this->assign('info',json_encode($info,true));
            return $this->fetch('groupForm');
        }
    }

    public function groupDel(){
        $level_id=input('level_id');
        if (empty($level_id)){
            return ['code'=>0,'msg'=>'会员组ID不存在！'];
        }
        db('user_level')->where(array('level_id'=>$level_id))->delete();
        return ['code'=>1,'msg'=>'删除成功！'];
    }

    public function groupOrder(){
        $userLevel=db('user_level');
        $data = input('post.');
        $userLevel->update($data);
        $result['msg'] = '排序更新成功!';
        $result['url'] = url('userGroup');
        $result['code'] = 1;
        return $result;
    }
    public function userGroup2(){
        if(request()->isPost()){
            $userLevel=db('user_tlevel');
            $list=$userLevel->order('sort')->select();
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        return $this->fetch();
    }

    public function groupEdit2(){
        if(request()->isPost()) {
            $data = input('post.');
            db('user_tlevel')->update($data);
            $result['msg'] = '会员组修改成功!';
            $result['url'] = url('userGroup2');
            $result['code'] = 1;
            return $result;
        }else{
            $map['level_id'] = input('param.level_id');
            $info = db('user_tlevel')->where($map)->find();
            $this->assign('title',lang('edit')."会员组");
            $this->assign('info',json_encode($info,true));
            return $this->fetch('groupForm2');
        }
    }
    public function groupDel2(){
        $level_id=input('level_id');
        if (empty($level_id)){
            return ['code'=>0,'msg'=>'会员组ID不存在！'];
        }
        db('user_tlevel')->where(array('level_id'=>$level_id))->delete();
        return ['code'=>1,'msg'=>'删除成功！'];
    }

    public function groupOrder2(){
        $userLevel=db('user_tlevel');
        $data = input('post.');
        $userLevel->update($data);
        $result['msg'] = '排序更新成功!';
        $result['url'] = url('userGroup2');
        $result['code'] = 1;
        return $result;
    }
    //升级记录
    public function uplevel(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('uplevel')
                ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.level as ulevel,u.uplevel,u.createtime,u.status as stus,u.cha,u.type_level,u.userid,ul.*')
                ->where('ul.email|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.createtime desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();

            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                $list['data'][$k]['level'] =getulevel_name($v['ulevel']) ;
                $list['data'][$k]['uplevel'] = getulevel_name($v['uplevel']);
                $list['data'][$k]['type_level'] = getpaytype($v['type_level']);
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
//升级操作
    public function uplevel_operate(){
        $id=input('post.id');
        $type=input('post.type');
        $uplevel=db('uplevel')->where('id',$id)->find();
        if($type==1){
            $user=db('users')->where('id',$uplevel['userid'])->find();
            db('users')->where('id',$uplevel['userid'])->setField('level',$uplevel['uplevel']);
            //           addarea($user['fatherid'],$uplevel['cha'],$user['treeplace']);
         //   bonus2($user['id'],$uplevel['cha']);
            //  lirunjiang($user['id'],$uplevel['cha']);
        }else{
            if($uplevel['type_level']==2){
                db('users')->where('id',$uplevel['userid'])->setInc('money_jifen',$uplevel['cha']);
            }
        }
        if(db('uplevel')->where('id='.$id)->update(array('status'=>$type))!==false){
            return ['code'=>1,'msg'=>'设置成功!'];
        }else{
            return ['code'=>0,'msg'=>'设置失败!'];
        }
    }
//服务中心列表
    public function server_list(){
            if(request()->isPost()){
                $key=input('post.key');
                $page =input('page')?input('page'):1;
                $pageSize =input('limit')?input('limit'):config('pageSize');
                $list=db('users')
                    ->where('server',1)
                    ->whereOr('server',2)
                    ->where('nickname|mobile|username','like',"%".$key."%")
                    ->order('jihuo_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
                if(!empty($list)){
                    foreach ($list['data'] as $k=>$v){
                        $list['data'][$k]['jihuo_time'] = date('Y-m-d H:i:s',$v['jihuo_time']);
                        $list['data'][$k]['is_ok'] =1;
                    }
                }
                return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
            }
            return $this->fetch();
    }
    //推荐结构
    public function tuijian(){
        $user=getuser(1);
        $this->assign('user', $user);
        return view();
    }
//设置服务中心
    public function server_ok(){
        $id=input('post.id');
        $is_lock=input('post.is_lock');
        if($is_lock==1){
            $is_ok=2;
        }else{
            $is_ok=0;
        }
            if(db('users')->where('id='.$id)->update(['server'=>$is_ok])!==false){
                return ['status'=>1,'msg'=>'设置成功!'];
            }else{
                return ['status'=>0,'msg'=>'设置失败!'];
            }
    }
    //业绩统计
    public  function  achievement(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('total_achievement')
                ->where('id','gt',0)
                ->order('createtime desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
                if($v['new_grant']>0){
                    $b1=sprintf("%.2f", $v['bonus1']/$v['new_grant']*100);
                    $b2=sprintf("%.2f",$v['bonus2']/$v['new_grant']*100);
                    $b3=sprintf("%.2f",$v['bonus3']/$v['new_grant']*100);
                    $b4=sprintf("%.2f",$v['bonus4']/$v['new_grant']*100);
                    $b5=sprintf("%.2f",$v['bonus5']/$v['new_grant']*100);
                    $b6=sprintf("%.2f",$v['bonus6']/$v['new_grant']*100);
                    $b7=sprintf("%.2f",$v['bonus7']/$v['new_grant']*100);
                    $b8=sprintf("%.2f",$v['bonus8']/$v['new_grant']*100);
                }else{
                    $b1=0;
                    $b2=0;
                    $b3=0;
                    $b4=0;
                    $b5=0;
                    $b6=0;
                    $b7=0;
                    $b8=0;
                }
                if($v['newadd_achievement']>0){
                    $b9=sprintf("%.2f",$v['new_grant']/$v['newadd_achievement']*100);
                 //   $b5=$v['new_grant']/$v['newadd_achievement']*100;
                }else{
                    $b9=0;
                }
                if($v['all_achievement']>0){
                    $b10=sprintf("%.2f",$v['all_grant']/$v['all_achievement']*100);
                 //   $b6=$v['all_grant']/$v['all_achievement']*100;
                }else{
                    $b10=0;
                }
                $list['data'][$k]['b1']=$b1;
                $list['data'][$k]['b2']=$b2;
                $list['data'][$k]['b3']=$b3;
                $list['data'][$k]['b4']=$b4;
                $list['data'][$k]['b5']=$b5;
                $list['data'][$k]['b6']=$b6;
                $list['data'][$k]['b7']=$b7;
                $list['data'][$k]['b8']=$b8;
                $list['data'][$k]['b9']=$b9;
                $list['data'][$k]['b10']=$b10;
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        $money_type11=db('money_type')->where('id',11)->value('type');
        $money_type12=db('money_type')->where('id',12)->value('type');
        $money_type13=db('money_type')->where('id',13)->value('type');
        $money_type14=db('money_type')->where('id',14)->value('type');
        $money_type15=db('money_type')->where('id',15)->value('type');
        $money_type16=db('money_type')->where('id',16)->value('type');
        $this->assign('money_type11',$money_type11);
        $this->assign('money_type12',$money_type12);
        $this->assign('money_type13',$money_type13);
        $this->assign('money_type14',$money_type14);
        $this->assign('money_type15',$money_type15);
        $this->assign('money_type16',$money_type16);
        return $this->fetch();
    }



}